jQuery.noConflict();
(function($) {
    $.h5Storage = function() {
        return new h5Storage()
    };
    var h5Storage = (function() {
        var h5Storage = function() {};
        h5Storage.prototype = {
            db: localStorage,
            get: function(key, isJson) {
                try {
                    return isJson === true ? JSON.parse(this.db.getItem(key)) : this.db.getItem(key)
                } catch(err) {
                    return null
                }
            },
            set: function(key, value, isJson) {
                try {
                    if (isJson === true) {
                        this.db.setItem(key, JSON.stringify(value))
                    } else {
                        this.db.setItem(key, value)
                    }
                } catch(err) {
                    console.log(err)
                }
            },
            remove: function(key) {
                try {
                    this.db.removeItem(key)
                } catch(err) {
                    console.log(err)
                }
            },
            clear: function(keylist, re) {
                try {
                    var self = this;
                    if (keylist instanceof Array) {
                        $.each(keylist, function(i, n) {
                            self.db.removeItem(n)
                        });
                        if (re === true) {
                            window.location.reload(false)
                        }
                    }
                } catch(err) {
                    console.log(err)
                }
            }
        };
        return h5Storage
    })()
})($);

(function($) {
    $.pdi = function() {
        return new pdi()
    };
    var pdi = (function() {
        var pdi = function() {};
        pdi.prototype = {
            get: function(part, key) {
                var config = h5Storage.get(part, true);
                if (config == null || config.lenght == 0 || (typeof key != 'undefined' && typeof config[key] == 'undefined')) {
                    if (typeof _config[part] == 'undefined') {
                        config = _config
                    } else {
                        config = _config[part]
                    }
                }
                if (typeof key == 'undefined') {
                    return config
                }
                return config[key]
            },
            set: function(part, key, value, data) {
                if (typeof data == 'undefined') {
                    data = h5Storage.get(part, true) ? h5Storage.get(part, true) : {}
                }
                if (key != "" && key != null) {
                    data[key] = value
                } else {
                    data = value
                }
                h5Storage.set(part, data, true)
            },
            length: function(data) {
                if (typeof data == 'undefined' || data == null || !(data instanceof Array)) {
                    return 0
                }
                return data.length
            },
            getSkins: function() {
                var _skins = _config.skins;
                var skins = PDI.get('skins');
                $.each(skins,
                function(i, n) {
                    _skins[i] = n
                });
                return _skins
            },
            getSkin: function(part, key) {
                var data = this.getSkins();
                if (!data[part] || typeof data[part] == 'undefined') {
                    return ''
                }
                if (typeof data[part][key] == 'undefined') {
                    if (typeof _config['skins'][part][key] != 'undefined') {
                        return _config['skins'][part][key]
                    } else {
                        return ''
                    }
                }
                return data[part][key]
            },
            setSkin: function(part, key, value, data) {
                if (part == 'skin_cloud' || part == 'skin_local') {
                    if (typeof data == 'undefined') {
                        data = h5Storage.get('skins', true) ? h5Storage.get('skins', true) : {}
                    }
                    if (typeof data[part] == 'undefined') {
                        data[part] = {}
                    }
                    data[part][key] = value;
                    h5Storage.set("skins", data, true);
                    if (part == 'skin_cloud') {
                        user.updateMsgId();
                        user.synchronize()
                    }
                }
            },
            getStyle: function(part, key) {
                var data = PDI.get('setup', 'style');
                if (typeof key == 'undefined') {
                    if (typeof data[part] == 'undefined') {
                        return _config['style'][part]
                    }
                    return data[part]
                }
                if (typeof data[part] == 'undefined' || typeof data[part][key] == 'undefined') {
                    return _config['style'][part][key]
                }
                return data[part][key]
            },
            setStyle: function(part, key, value, data) {
                if (typeof data == 'undefined') {
                    data = h5Storage.get('setup', true) ? h5Storage.get('setup', true) : {}
                }
                if (typeof data['style'] == 'undefined') {
                    data['style'] = {};
                    data['style'][part] = {}
                } else if (typeof data["style"][part] == 'undefined') {
                    data['style'][part] = {}
                }
                data['style'][part][key] = value;
                h5Storage.set('setup', data, true);
                user.updateMsgId();
                user.synchronize()
            },
            insertDialbox: function(value, data) {
                if (typeof data == 'undefined') {
                    data = PDI.get('dialBoxes', 'webSite')
                }
                data.push(value);
                PDI.set('dialBoxes', 'webSite', data);
                user.updateMsgId();
                user.synchronize()
            },
            updateDialbox: function(index, value, data) {
                if (typeof data == 'undefined') {
                    data = PDI.get('dialBoxes', 'webSite')
                }
                data[index] = value;
                PDI.set('dialBoxes', 'webSite', data);
                user.updateMsgId();
                user.synchronize()
            },
            removeDialbox: function(index, data) {
                if (typeof data == 'undefined') {
                    data = PDI.get('dialBoxes', 'webSite')
                }
                if (index < this.length(data)) {
                    data[index]['isDel'] = true;
                    PDI.set('dialBoxes', 'webSite', data);
                    user.updateMsgId();
                    user.synchronize()
                }
            },
            destoryDialbox: function(index, data) {
                if (typeof data == 'undefined') {
                    data = PDI.get('dialBoxes', 'webSite')
                }
                if (index < this.length(data)) {
                    data.splice(index, 1)
                }
                PDI.set('dialBoxes', 'webSite', data)
            },
            changeDialbox: function(fromIndex, toIndex, data) {
                if (typeof data == 'undefined') {
                    data = PDI.get('dialBoxes', 'webSite')
                }
                if (fromIndex < 0 || fromIndex >= this.length(data) || toIndex < 0 || toIndex >= this.length(data)) {
                    return false
                }
                var tmp = data[toIndex];
                data[toIndex] = data[fromIndex];
                data[fromIndex] = tmp;
                PDI.set('dialBoxes', 'webSite', data);
                user.updateMsgId();
                user.synchronize()
            },
            moveDialbox: function(fromIndex, toIndex, data) {
                if (typeof data == 'undefined') {
                    data = PDI.get('dialBoxes', 'webSite')
                }
                if (fromIndex < 0 || fromIndex >= this.length(data) || toIndex < 0 || toIndex >= this.length(data)) {
                    return false
                }
                var tmp = data[fromIndex];
                this.destoryDialbox(fromIndex, data);
                data.splice(toIndex, 0, tmp);
                PDI.set('dialBoxes', 'webSite', data);
                user.updateMsgId();
                user.synchronize()
            },
            appendDialbox: function(toIndex, value, data) {
                if (typeof data == 'undefined') {
                    data = PDI.get('dialBoxes', 'webSite')
                }
                data.splice(toIndex, 0, value);
                PDI.set('dialBoxes', 'webSite', data);
                user.updateMsgId();
                user.synchronize()
            },
            insertAppDialbox: function(value, data) {
                if (typeof data == 'undefined') {
                    data = PDI.get('dialBoxes', 'app')
                }
                data.push(value);
                PDI.set('dialBoxes', 'app', data);
                user.updateMsgId();
                user.synchronize()
            },
            destoryAppDialbox: function(index, data) {
                if (typeof data == 'undefined') {
                    data = PDI.get('dialBoxes', 'app')
                }
                if (index < this.length(data)) {
                    data.splice(index, 1)
                }
                PDI.set('dialBoxes', 'app', data);
                user.updateMsgId();
                user.synchronize()
            },
        };
        return pdi
    })()
})($);

(function($) {
    $.user = function() {
        return new user()
    };
    var user = (function() {
        var user = function() {
        	this.sign = 'newTabs';
        };
        user.prototype = {
            updateMsgId: function(msgid) {
                if (typeof msgid == 'undefined') {
                    msgid = parseInt(PDI.get('setup', 'msgid')) + 1
                }
                PDI.set('setup', 'msgid', msgid)
            },
            synchronize: function() {
                var self = this;
            }
        };
        return user
    })()
})($);

(function($) {
    $.fn.dialog = function(opt) {
        return new dialog(this, opt)
    };
    $.dialog = function(opt) {
        return new dialog('', opt)
    };
    var dialog = (function(el, opt) {
        var dialog = function(el, opt) {
            var self = this;
            $.each(opt, function(i, n) {
                self[i] = n
            });
            if (el == '') {
                if (typeof self.callback.initialize == 'function') {
                    self.callback.initialize.call(self)
                } else {
                    self.show()
                }
            } else {
                self.eventObj = el;
                self.eventObj.unbind(self.eventName).bind(self.eventName, function() {
                    if (typeof self.callback.initialize == 'function') {
                        self.callback.initialize.call(self, $(this))
                    }
                })
            }
        };
        dialog.prototype = {
            id: "",
            caption: "",
            content: "",
            eventObj: "",
            eventName: "click",
            callback: {},
            isLock: false,
            isFixed: false,
            isDestory: false,
            isFollow: false,
            followObj: "",
            isArrow: false,
            animate: "",
            style: "",
            zIndex: 100,
            lock: function() {
                var self = this;
                if (!self.isLock) {
                    return
                }
                var maskdiv = $('<div class="dialogMask"></div>').css({
                    "z-index": self.zIndex
                });
                $("body").append(maskdiv)
            },
            unlock: function() {
                $("body").find(".dialogMask").remove()
            },
            position: function() {
                var self = this;
                var dbox = $("#" + self.id);
                if (!self.isFollow) {
                    if (self.style != '') {
                        dbox.css(this.style)
                    } else {
                        dbox.css({
                            "top": "50%",
                            "left": "50%",
                            "margin-left": "-" + parseInt(dbox[0].offsetWidth / 2) + "px",
                            "margin-top": "-" + parseInt(dbox[0].offsetHeight / 2) + "px",
                        })
                    }
                }
                dbox.css({
                    "z-index": this.zIndex + 1
                })
            },
            follow: function() {
                var self = this;
                if (!self.isFollow || (self.eventObj == '' && self.followObj == '')) {
                    return
                }
                if (self.followObj == "") {
                    var coffset = self.eventObj.offset();
                    var width = parseInt(self.eventObj.get().offsetWidth / 2)
                } else {
                    var coffset = self.followObj.offset();
                    var width = parseInt(self.followObj.get().offsetWidth / 2)
                }
                var dialogCoffset = {};
                dialogCoffset['left'] = coffset.left - 30,
                dialogCoffset['top'] = coffset.top + 40,
                dialogCoffset['right'] = document.body.offsetWidth - coffset.left - width - 42,
                dialogCoffset['bottom'] = document.body.offsetHeight - coffset.top + 10;
                var _tmpFollow = self.isFollow.split(' ');
                $.each(_tmpFollow,
                function(i, n) {
                    $("#" + self.id).css(n, dialogCoffset[n] + 'px')
                })
            },
            show: function() {
                var self = this;
                if ($("#" + self.id).hasClass('dialog-visible')) {
                    self.remove();
                    return
                }
                self.lock();
                if ($("#" + self.id).length == 0) {
                    if (self.isArrow) {
                        var arrow = self.isArrow.replace(' ', '');
                        var arrow_tmp = arrow.split(',');
                        arrow = arrow_tmp[0];
                        var arrowColor = typeof arrow_tmp[1] == 'undefined' ? '': arrow_tmp[1];
                        var arrowHtml = '<div class="' + arrow + '_arrow-border"></div><div class="' + arrow + arrowColor + '_arrow"></div>'
                    } else {
                        var arrowHtml = ''
                    }
                    if (this.caption == "") {
                        var dbox = $('<div>' + arrowHtml + '<button class="close"></button><div class="main"></div></div>')
                    } else {
                        var dbox = $('<div>' + arrowHtml + '<div class="head"><div class="title">' + this.caption + '</div><button class="close"></button></div><div class="main"></div></div>')
                    }
                    dbox.find(".main").append(this.content);
                    dbox.addClass('dialog').attr('id', this.id);
                    $("body").append(dbox);
                    dbox.find(".close").bind("click",
                    function() {
                        self.remove();
                        return false
                    });
                    this.position();
                    if (this.animate != "") {
                        dbox.css({
                            "-webkit-transform-origin": this.animate
                        })
                    }
                    self.follow()
                } else {
                    var dbox = $("#" + this.id)
                }
                window.setTimeout(function() {
                    dbox.addClass('dialog-visible')
                },
                0);
                window.setTimeout(function() {
                    $(document).unbind('click').bind('click',
                    function(e) {
                        var targetObj = $(e.target);
                        if (!targetObj.hasClass('lastVisited') && self.id == "appSetupDialog" && (targetObj.hasClass('appItemSub') || targetObj.hasClass('sub') || targetObj.hasClass('appItem'))) {
                            return false
                        }
                        if (!isContains(e.target, dbox.get())) {
                            self.remove();
                            return false
                        }
                    })
                },
                0)
            },
            changeContent: function(content) {
                var self = this;
                var dbox = $("#" + self.id);
                if (dbox.length > 0) {
                    self.content = content;
                    dbox.find(".main").empty().append(content)
                }
            },
            remove: function() {
                var self = this;
                var dbox = $("#" + self.id);
                self.unlock();
                if (typeof self.callback.dialogClose == 'function') {
                    self.callback.dialogClose.call(self)
                }
                dbox.removeClass('dialog-visible');
                $(document).unbind('click');
                if (self.isDestory) {
                    setTimeout(function() {
                        self.destory()
                    },
                    300)
                }
            },
            destory: function() {
                var self = this;
                var dbox = $("#" + self.id);
                dbox.remove()
            }
        };
        return dialog
    })()
})($);


var _move = false,
	_down = false,
	_flip = true,
	_wheel = true,
	_wheelEvent = true,
	_resize = false,
	_destory = false,
	_downfun = "",
	_flipfun = "",
	_x = 0,
	_y = 0,
	eventObj = '',
	eclone = '',
	containerOffset = '',
	onDragID = '',
	onTargetID = '',
	onSelectedID = '',
	trends = [],
	readyID = '',
	_cx = 0,
	_cy = 0,
	_cw = 0,
	_ch = 0;


// box
(function($) {
    $.box = function(id, dbox) {
        return new box(id, dbox)
    };
    var box = (function(id, dbox) {
        var box = function(id, dbox) {
            var self = this;
            self.boxOptions = {
                id: id,
                title: '',
                img: '',
                icon: '',
                url: '',
                desc: '',
                isApp: false,
                isDel: false,
                isCreate: false,
                isFixed: false,
                isVirtual: false,
                isNew: false
            };
            self.set(null, dbox);
            self.create()
        };
        box.prototype = {
            boxObject: '',
            set: function(key, value) {
                var self = this;
                if (key == '' || key == null) {
                    $.each(value,
                    function(i, n) {
                        self.boxOptions[i] = n
                    })
                } else {
                    self.boxOptions[key] = value
                }
            },
            getImg: function() {
            	
                var self = this;
                if (self.boxOptions.img != "") {
                    return self.boxOptions.img.trim()
                }
                var img = self.boxOptions.url.trim();
                if (img == '') {
                    return urlImg + 'ie_logo.png'
                }
                img = img.toLowerCase().replace(/%3a%2f%2f/ig, '://');
                var imgMatch = img.match(/:\/\/[^\/]+/g);
                if (imgMatch == null) {
                    img = "http://" + img;
                    imgMatch = img.match(/:\/\/[^\/]+/g)
                }
                img = imgMatch.pop();
                img = img.substr(3);
                img = img.replace(/^www\./, '');
                if (img == '' || img.indexOf('.') == -1 || img.indexOf('.') == img.length - 1) {
                    return urlImg + 'ie_logo.png'
                }
                return urlImg + 'app/' + img + '.png'
            },
            getUrl: function() {
                var self = this,
                url = self.boxOptions.url.trim();
                if (url == '') {
                    return ''
                }
                url = url.replace(/%3a%2f%2f/ig, '://').trim();
                var index = url.indexOf("://");
                if (index > 0 && index < 20) {
                    return url
                }
                if (url.substring(0, 4) !== "http") {
                    return "http://" + url
                }
            },
            getIcon: function() {
            	
                var self = this,
                url = self.boxOptions.url.trim(),
                iconUrl = '',
                iconColor = '';
                if (url == '') {
                    return ''
                }
                url = url.toLowerCase().replace(/%3a%2f%2f/ig, '://').trim();
                var urlMatch = url.match(/:\/\/[^\/]+/g);
                if (urlMatch == null) {
                    url = "http://" + url;
                    urlMatch = url.match(/:\/\/[^\/]+/g)
                }
                url = urlMatch.pop();
                url = url.substr(3);
                if (typeof favicons[url] == 'undefined') {
                    //iconUrl = 'chrome://favicon/size/16/http://' + url
                	iconUrl = urlImg + 'app/default_icon.ico';
                } else {
                    if (typeof favicons[url]['ico'] != 'undefined') {
                        iconUrl = favicons[url]['ico']
                    } else {
                        iconUrl = 'http://' + url + '/favicon.ico'
                    }
                    if (typeof favicons[url]['rgb'] != 'undefined') {
                        iconColor = favicons[url]['rgb']
                    }
                }
                return {
                    'iconUrl': iconUrl,
                    'iconColor': iconColor
                }
            },
            create: function() {
                var self = this;
                var iconObj = self.getIcon();
                var boxItem = $('<div class="appBox' + (self.boxOptions.isNew ? ' new': '') + (self.boxOptions.isCreate ? ' boxCreate': '') + (self.boxOptions.isFixed ? ' boxFixed': '') + (self.boxOptions.isVirtual ? ' boxVirtual': '') + '" id="appBox_' + self.boxOptions.id + '" url="' + self.getUrl() + '"></div>').append($('<div class="boxLogo" notes="' + self.boxOptions.title + '"></div>').append(iconObj == '' ? '': $('<div class="boxIcon"></div>').css('background-image', 'url(' + iconObj.iconUrl + ')')).append(self.boxOptions.isCreate == false ? '': $('<div class="boxPlus"><div class="vertical"></div><div class="horizontal"></div></div>'))).append($('<div class="boxTitle' + (self.boxOptions.isCreate ? ' boxPlus': '') + '"></div>').html('<a>' + self.boxOptions.title + '</a>'));
                self.boxObject = boxItem
            }
        };
        return box
    })();
	
    $.fn.dialbox = function(opt) {
        return new dialbox(this, opt)
    };
    var dialbox = (function(el, opt) {
        var dialbox = function(el, opt) {
            var self = this;
            $.each(opt, function(i, n) {
                self[i] = n
            });
            if (self.height === false) {
                self.height = Math.round(self.width * 0.625) + 32
            } else {
                self.height = self.height + 32
            }
            self.container = el;
            self.init();
            $(window).bind('resize', function() {
                if (!_resize || document.body.offsetWidth > 100) {
                    _resize = true;
                    self.position();
                    window.setTimeout(function() {
                        _resize = false
                    },
                    300)
                }
            });
            function wheel(event) {
                if ($('.dialog-visible').length == 0 && $('.searchdialog').css('display') != 'block') {
                    if (_wheelEvent) {
                        _wheelEvent = false;
                        var delta = 0;
                        if (!event) event = window.event;
                        if (event.wheelDelta) {
                            delta = delta + event.wheelDelta
                        } else if (event.detail) {
                            delta = delta + ( - event.detail * 40)
                        }
                        if (delta > 0) {
                            if (_wheel || $('.dialbox').get().scrollTop <= 0) {
                                self.loadBoxes('pre')
                            }
                        } else if (delta < 0) {
                            if (_wheel || $('.dialbox').get().offsetHeight + $('.dialbox').get().scrollTop >= $('.dialbox').get().scrollHeight) {
                                self.loadBoxes('next')
                            }
                        }
                        if (event.preventDefault) event.preventDefault();
                        event.returnValue = true;
                        setTimeout(function() {
                            _wheelEvent = true
                        },
                        600)
                    }
                }
            }
            if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);
            window.onmousewheel = wheel
        };
        dialbox.prototype = {
            container: "",
            containerWidth: 0,
            containerHeight: 0,
            containerLeft: 0,
            containerTop: 0,
            pageSwitcher: "",
            pageIndexSwitcher: "",
            pageSwitcherShow: false,
            titleShow: true,
            createBoxShow: false,
            cols: 4,
            rows: 3,
            num: 12,
            page: 1,
            totalnum: 0,
            totalPage: 1,
            opacity: 0.8,
            spacing: 15,
            border: 1,
            width: 214,
            height: 166,
            radius: 2,
            heightBlank: 0,
            widthBlank: 0,
            show_type: 0,
            init: function() {
                var self = this;
                self.container.empty();
                var _boxes = PDI.get('dialBoxes', 'webSite').concat();
                var _realBoxs = [];
                var hasDel = false;
                $.each(_boxes,
                function(i, n) {
                    if (n.isDel == true) {
                        hasDel = true
                    } else {
                        _realBoxs.push(n)
                    }
                });
                if (hasDel) {
                    PDI.set('dialBoxes', 'webSite', _realBoxs)
                } else {
                    _realBoxs = null
                }
                self.addBoxes();
                self.position()
            },
            position: function() {
                var self = this;
                self.measurement();
                self.container.css({
                    "width": self.containerWidth + "px",
                    "left": self.containerLeft + "px",
                    "height": self.containerHeight + "px",
                    "top": self.containerTop + "px"
                });
                self.positionBox()
            },
            positionBox: function() {
                var self = this;
                var boxList = self.container.find('.appBox'),
                not_boxDrag = boxList.not('.boxDrag');
                if (self.titleShow) {
                    self.container.find('.boxLogo').removeClass('noTitle')
                } else {
                    self.container.find('.boxLogo').addClass('noTitle')
                }
                if (self.radius > 30) {
                    if (!self.titleShow) {
                        self.container.find('.boxTitle').css('background-color', 'transparent');
                        self.container.find('.boxTitle').css('bottom', '50px')
                    }
                } else {
                    if (!self.titleShow) {
                        if (boxList.length > 0) {
                            for (var i = 0; i < boxList.length; i++) {
                                var icolor = $(boxList[i]).find('.boxTitle').attr('icolor');
                                $(boxList[i]).find('.boxTitle').css('background-color', 'rgba(' + icolor + ')')
                            }
                        }
                        self.container.find('.boxTitle').css('bottom', '0px')
                    }
                }
                self.container.find('.boxLogo').css('border-radius', self.radius + 'px');
                if (self.radius <= 30 && !self.titleShow) {
                    self.container.find('.boxTitle').css({borderTopLeftRadius: self.radius + 'px',borderTopRightRadius:self.radius + 'px'})
                }
                if (self.radius > 30) {
                    self.container.find('.boxIcon').hide()
                } else {
                    self.container.find('.boxIcon').show()
                }
                if (self.spacing == 0 || self.radius > 30) {
                    self.container.find('.boxLogo').css('border-bottom-width', '0px')
                } else {
                    self.container.find('.boxLogo').css('border-bottom-width', '2px')
                }
                window.setTimeout(function() {
                    self.container.addClass('op_' + self.opacity * 10);
                    if (not_boxDrag.length > 0) {
                        for (var i = 0; i < not_boxDrag.length; i++) {
                            $(not_boxDrag[i]).css({
                                "width": self.width + "px",
                                "height": (self.titleShow == false ? (self.height - 32) : self.height) + "px",
                                "left": self.spacing + (i % self.cols) * (self.spacing + self.width + 2 * self.border) + 'px',
                                "top": self.spacing + parseInt(i / self.cols) * (self.spacing + (self.titleShow == false ? (self.height - 32) : self.height) + 2 * self.border) + 'px',
                                "display": "block"
                            })
                        }
                    }
                },
                0);
                if (!not_boxDrag) {
                    not_boxDrag.css("-webkit-transition", "left .2s ease-in, top .2s ease-in, opacity .2s ease-in")
                }
                self.pageIndex()
            },
            adaptive: function(cols, rows, type) {
                var self = this;
                self.width = parseInt((screenWidth - ((cols + 3) * self.spacing) - (cols * 2 * self.border) - parseInt(self.widthBlank * screenWidth)) / cols);
                var dialboxLogoHeight = parseInt((screenHeight - ((rows + 3) * self.spacing) - (rows * 2 * self.border) - parseInt(self.heightBlank * screenHeight) - 246) / rows);
                self.height = self.titleShow ? dialboxLogoHeight: dialboxLogoHeight + 32;
                if (type == 'square') {
                    self.width = dialboxLogoHeight;
                    self.height = self.titleShow ? dialboxLogoHeight + 32 : dialboxLogoHeight
                }
            },
            measurement: function() {
                var self = this;
                var bodyWidth = document.body.offsetWidth - parseInt(self.widthBlank * screenWidth),
                bodyHeight = document.body.offsetHeight - parseInt(self.heightBlank * screenHeight) - 145;
                if (bodyWidth == 0 && bodyHeight == 0) {
                    return false
                }
                var bodyRatio = bodyWidth / bodyHeight,
                ratioDiffAbs = '',
                matrix = {};
                if (bodyWidth != 0) {
                    self.container.show()
                }
                var maxCols = parseInt((bodyWidth - 3 * self.spacing) / (self.width + self.spacing + 2 * self.border));
                for (cols = 1; cols <= maxCols; cols++) {
                    if (self.num % cols == 0) {
                        matrix[cols] = {
                            "rows": self.num / cols,
                            "cols": cols
                        }
                    }
                }
                $.each(matrix,
                function(i, n) {
                    var itemWidth = self.width + self.spacing + 2 * self.border,
                    itemHeight = (self.titleShow == false ? (self.height - 32) : self.height) + self.spacing + 2 * self.border,
                    curRatio = (n.cols * itemWidth + 3 * self.spacing) / (n.rows * itemHeight + 3 * self.spacing),
                    curRatioDiffAbs = Math.abs(1 - (curRatio / bodyRatio));
                    if (curRatioDiffAbs < ratioDiffAbs || ratioDiffAbs == '') {
                        ratioDiffAbs = curRatioDiffAbs;
                        self.containerWidth = n.cols * itemWidth + self.spacing;
                        self.containerLeft = parseInt((document.body.offsetWidth - self.containerWidth) / 2);
                        self.containerHeight = n.rows * itemHeight + self.spacing;
                        self.containerTop = parseInt((document.body.offsetHeight - 90 - self.containerHeight) / 2);
                        self.cols = n.cols;
                        self.rows = n.rows
                    }
                })
            },
            getBoxes: function() {
                var self = this,
                sum = 0;
                var _boxes = PDI.get('dialBoxes', 'webSite').concat();
                if (self.createBoxShow) {
                    _boxes.push({
                        title: getI18nMsg('boxCreateTitle'),
                        isCreate: true,
                        isFixed: true,
                        isVirtual: true
                    })
                }
                $.each(_boxes, function(i, n) { // alert(n.type) //这里获取配置文件
                            if (!n.isDel && (self.show_type == 0 || self.show_type == n.type)) {
                                sum++
                            }
                        });
                self.totalnum = sum;
                return _boxes
            },
            addBoxes: function(order) {
                var self = this;
                var existNum = $(self.container.find('.appBox').not('.boxDrag')).length;
                var boxes = self.getBoxes();
                self.totalPage = ((self.totalnum % self.num) == 0) ? (self.totalnum / self.num) : parseInt(self.totalnum / self.num) + 1;
                self.page = self.page > self.totalPage ? self.totalPage: self.page;
                var page = self.page,
                start = (page - 1) * self.num,
                end = start + (self.num * 1) - existNum,
                index = 0,
                realIndex = 0,
                boxQueue = [];
                $.each(boxes, function(i, n) {
                	if (!n.isDel && (self.show_type == 0 || self.show_type == n.type)) {
                        if (typeof order != 'undefined' && order == 'pre') {
                            if (realIndex == end) {
                                readyID = i
                            }
                        } else {
                            if (realIndex == start) {
                                readyID = i
                            }
                        }
                        realIndex++;
                        if (('appBox_' + i) == onDragID) {
                            return
                        }
                        if (index >= start && index < end) {
                            boxQueue.push({
                                "id": i,
                                "box": n
                            })
                        }
                        index++
                    }
                });
                if (typeof order != 'undefined' && order == 'pre') {
                    for (var i = boxQueue.length - 1; i >= 0; i--) {
                        self.addBox(boxQueue[i]['id'], boxQueue[i]['box'], order)
                    }
                } else {
                    for (var i = 0; i < boxQueue.length; i++) {
                        self.addBox(boxQueue[i]['id'], boxQueue[i]['box'], order)
                    }
                }
                PDI.set('setup', 'dialBoxPage', self.page)
            },
            addBox: function(id, box, order) {
                var self = this,
                thisBox = $.box(id, box);
                var logoImg = new Image(),
                logoImgUrl = thisBox.getImg();
                var logoBoxHeight = self.titleShow == false ? (self.height - 32) : self.height;
                var logoBoxWidth = self.width;
                logoImg.onload = function() {
                    if (logoImg.width == 380 && logoImg.height == 160) {
                        thisBox.boxObject.find('.boxLogo').css({
                            'background-image': thisBox.boxOptions.isCreate == true ? '': 'url(' + logoImgUrl + ')',
                            '-webkit-background-size': 'auto 100%',
                            'background-position': 'left'
                        })
                    } else {
                        if (logoImg.width > logoBoxWidth || logoImg.height > logoBoxHeight) {
                            thisBox.boxObject.find('.boxLogo').css({
                                'background-image': thisBox.boxOptions.isCreate == true ? '': 'url(' + logoImgUrl + ')',
                                '-webkit-background-size': (logoImg.width / logoImg.height > logoBoxWidth / logoBoxHeight) ? '100% auto': 'auto 100%',
                                'background-position': 'center center'
                            })
                        } else {
                            thisBox.boxObject.find('.boxLogo').css({
                                'background-image': thisBox.boxOptions.isCreate ? '': 'url(' + logoImgUrl + ')'
                            })
                        }
                    }
                };
                logoImg.src = logoImgUrl;
                var iconObj = thisBox.getIcon();
                if (self.titleShow) {
                    thisBox.boxObject.find('.boxTitle').css('background-color', 'transparent')
                }
                if (iconObj != '') {
                    if (iconObj.iconColor == '') {
                        var boxFavicon = new Image();
                        try {
                            boxFavicon.onload = function() {
                                try {
                                    var notColorList = new Array('0,0,0', '255,255,255', '240,240,240', '192,192,192');
                                    var boxFaviconCanvas = $('<canvas width="16" height="16"></canvas>').get();
                                    boxFaviconCanvas = boxFaviconCanvas.getContext("2d");
                                    boxFaviconCanvas.drawImage(boxFavicon, 0, 0);
                                    var imageData = boxFaviconCanvas.getImageData(8, 8, 1, 1).data;
                                    var imageDataRgba = imageData[0] + ',' + imageData[1] + ',' + imageData[2];
                                    if (notColorList.indexOf(imageDataRgba) > -1) {
                                        imageData = boxFaviconCanvas.getImageData(4, 4, 1, 1).data;
                                        imageDataRgba = imageData[0] + ',' + imageData[1] + ',' + imageData[2]
                                    }
                                    if (notColorList.indexOf(imageDataRgba) == -1) {
                                        thisBox.boxObject.find('.boxTitle').attr('icolor', imageDataRgba + ',.4');
                                        thisBox.boxObject.find('.boxLogo').css('border-bottom-color', 'rgba(' + imageDataRgba + ',.6)');
                                        if (!self.titleShow) {
                                            thisBox.boxObject.find('.boxTitle').css('background-color', 'rgba(' + imageDataRgba + ',.4)')
                                        }
                                    }
                                    if (self.radius > 30) {
                                        thisBox.boxObject.find('.boxTitle').css('background-color', 'transparent')
                                    }
                                } catch(err) {}
                            };
                            boxFavicon.src = iconObj.iconUrl
                        } catch(err) {}
                    } else {
                        thisBox.boxObject.find('.boxTitle').attr('icolor', iconObj.iconColor + ',.4');
                        thisBox.boxObject.find('.boxLogo').css('border-bottom-color', 'rgba(' + iconObj.iconColor + ',.6)');
                        if (!self.titleShow) {
                            thisBox.boxObject.find('.boxTitle').css('background-color', 'rgba(' + iconObj.iconColor + ',.4)')
                        }
                        if (self.radius > 30) {
                            thisBox.boxObject.find('.boxTitle').css('background-color', 'transparent')
                        }
                    }
                }
                self.dragBox(thisBox);
                self.removeBox(thisBox);
                if (typeof order != 'undefined' && order == "pre") {
                    self.container.prepend(thisBox.boxObject)
                } else {
                    self.container.append(thisBox.boxObject)
                }
                if (box.isNew) {
                    box.isNew = false;
                    PDI.updateDialbox(id, box)
                }
                return thisBox
            },
            appendBox: function(startIndex, top, left) {
                var self = this;
                var page = self.page;
                var existNum = $(self.container.find('.appBox').not('.boxDrag')).length;
                var boxes = self.getBoxes(),
                start = (page - 1) * self.num + startIndex,
                end = start + (self.num * 1) - existNum,
                index = 0,
                iBox = '';
                if (start > self.totalnum - 1) {
                    return false
                }
                $.each(boxes,
                function(i, n) {
                    if (!n.isDel && ('appBox_' + i) != onDragID) {
                        if (index >= start && index < end) {
                            iBox = {
                                "id": i,
                                "box": n
                            };
                            return false
                        }
                        index++
                    }
                });
                var thisBox = self.addBox(iBox['id'], iBox['box']);
                if (!self.titleShow) {
                    thisBox.boxObject.find('.boxLogo').addClass('noTitle')
                }
                if (self.radius > 30) {
                    if (!self.titleShow) {
                        thisBox.boxObject.find('.boxTitle').css('background-color', 'transparent');
                        thisBox.boxObject.find('.boxTitle').css('bottom', '50px')
                    }
                }
                thisBox.boxObject.find('.boxLogo').css('border-radius', self.radius + 'px');
                if (self.radius <= 30 && !self.titleShow) {
                    self.container.find('.boxTitle').css({borderRadiusTopleft: self.radius + 'px',borderRadiusTopright:self.radius + 'px'})
                }
                if (self.spacing == 0 || self.radius > 30) {
                    thisBox.boxObject.find('.boxLogo').css('border-bottom-width', '0px')
                }
                thisBox.boxObject.css({
                    "width": self.width + "px",
                    "height": (self.titleShow == false ? (self.height - 32) : self.height) + "px",
                    "top": top,
                    "left": left,
                    "display": "block"
                });
            },
            removeBox: function(box) {
                var self = this;
                box.boxObject.find('.boxClose').unbind('click').bind('click',
                function() {
                    PDI.removeDialbox(box.boxObject.attr('id').replace('appBox_', ''));
                    parent.installWebSites.splice(parent.installWebSites.indexOf(box.boxObject.attr('url')), 1);
                    self.totalnum = self.totalnum - 1;
                    if (self.totalnum % self.num == 0 && self.totalPage > 1) {
                        self.totalPage = self.totalPage - 1
                    }
                    self.pageIndex();
                    var boxlist = self.container.find('.appBox');
                    var thisIndex = boxlist.indexOf(box.boxObject.get());
                    var lastTop = $(boxlist[boxlist.length - 1]).css('top'),
                    lastLeft = $(boxlist[boxlist.length - 1]).css('left');
                    box.boxObject.css({
                        //"-webkit-transition": "all .2s ease-out",
                        "-webkit-transform-origin": "middle center"
                    }).empty();
                    window.setTimeout(function() {
                        box.boxObject.css({
                            "background": "-webkit-gradient(linear, left top, left bottom, from(rgba(0,0,0,0.5)), color-stop(0.5, rgba(0,0,0,1)), to(rgba(0,0,0,0.5)))",
                            "height": "0px",
                            "margin-top": parseInt((self.titleShow == false ? (self.height - 32) : self.height) / 2) + "px",
                            "border-radius": "8px"
                        })
                    },
                    0);
                    window.setTimeout(function() {
                        box.boxObject.remove();
                        for (var index = boxlist.length - 1; index > thisIndex; index--) {
                            $(boxlist[index]).css({
                                "top": $(boxlist[index - 1]).css('top'),
                                "left": $(boxlist[index - 1]).css('left')
                            })
                        }
                        window.setTimeout(function() {
                            self.appendBox(boxlist.length - 1, lastTop, lastLeft)
                        },
                        200)
                    },
                    220)
                })
            },
            dragBox: function(box) {
                var self = this;
                box.boxObject.unbind('mousedown').bind('mousedown', function(e) {
                    if (e.button == 2) {
                        return false
                    }
                    targetObj = $(e.target);
                    if (targetObj.hasClass('boxEdit') || targetObj.hasClass('boxClose') || targetObj.hasClass('boxPlus') || targetObj.hasClass('vertical') || targetObj.hasClass('horizontal')) {
                        return false
                    }
                    eventObj = $(this);
                    _move = false;
                    _down = true;
                    var coffset = eventObj.offset();
                    _cx = coffset.left;
                    _cy = coffset.top;
                    _cw = parseInt(eventObj.css('width'));
                    _ch = parseInt(eventObj.css('height'));
                    containerOffset = self.container.offset();
                    _downfun = setTimeout(function() {
                        if (_down == true) {
                            onDragID = eventObj.attr("id");
                            _x = e.pageX - parseInt(eventObj.css("left"));
                            _y = e.pageY - parseInt(eventObj.css("top"));
                            eclone = eventObj.clone();
                            eclone.addClass("boxClone");
                            eclone.css("visibility", "hidden");
                            eclone.insertAfter(eventObj);
                            if (eventObj.hasClass('boxCreate')) {}
                            eventObj.css({
                                "opacity": 0.3,
                                "border": "2px #333 dashed",
                                "z-index": getMaxZindex(eventObj) + 1,
                                "-webkit-transition": ""
                            });
                            eventObj.children().css("cursor", "move");
                            eventObj.addClass('boxDrag');
                            _move = true
                        }
                    },
                    300)
                });
                $(document).unbind("mousemove").bind("mousemove", function(e) {
                    if (_down == true && _move == false) {
                        if (e.pageX < _cx || e.pageX > (_cx + _cw) || e.pageY < _cy || e.pageY > (_cy + _ch)) {
                            if (_downfun) {
                                clearTimeout(_downfun);
                                _down = false
                            }
                        }
                        return false
                    }
                    if (_move) {
                        eventObj.css({
                            top: (e.pageY - _y) + 'px',
                            left: (e.pageX - _x) + 'px'
                        });
                        if (e.pageX > (parseInt(containerOffset.left) + parseInt(eventObj.parent().css('width'))) || e.pageX < parseInt(containerOffset.left)) {
                            if (_flip) {
                                _flip = false;
                                if (e.pageX > (parseInt(containerOffset.left) + parseInt(eventObj.parent().css('width')))) {
                                    self.loadBoxes('next')
                                } else {
                                    self.loadBoxes('pre')
                                }
                                eclone.attr('id', 'appBox_' + readyID);
                                onTargetID = 'appBox_' + readyID;
                                if (onTargetID != '') {
                                    if (eventObj.hasClass('boxVirtual')) {
                                        if (eventObj.hasClass('boxCreate')) {
                                            var boxData = {
                                                title: getI18nMsg('boxCreateTitle'),
                                                isCreate: true
                                            }
                                        }
                                        eventObj.removeClass('boxVirtual');
                                        PDI.appendDialbox(parseInt(onTargetID.replace('appBox_', '')), boxData)
                                    } else {
                                        PDI.moveDialbox(parseInt(onDragID.replace('appBox_', '')), parseInt(onTargetID.replace('appBox_', '')))
                                    }
                                }
                                onDragID = 'appBox_' + readyID;
                                var coffset = eclone.offset();
                                _cx = coffset.left;
                                _cy = coffset.top;
                                _cw = parseInt(eclone.css('width'));
                                _ch = parseInt(eclone.css('height'));
                                var _flipfun = setTimeout(function() {
                                    _flip = true
                                },
                                1500)
                            }
                        } else {
                            if (_flipfun != '') {
                                clearTimeout(_flipfun)
                            }
                        }
                        var offsetPageX = e.pageX - parseInt(containerOffset.left);
                        var offsetPageY = e.pageY - parseInt(containerOffset.top);
                        if (e.pageX < _cx || e.pageX > (_cx + _cw) || e.pageY < _cy || e.pageY > (_cy + _ch)) {
                            var eventObjSiblings = eventObj.siblings().not('.boxClone');
                            if (eventObjSiblings.length > 0) {
                                for (var i = 0; i < eventObjSiblings.length; i++) {
                                    boxtop = parseInt($(eventObjSiblings[i]).css("top"));
                                    boxleft = parseInt($(eventObjSiblings[i]).css("left"));
                                    boxwidth = parseInt($(eventObjSiblings[i]).css("width"));
                                    boxheight = parseInt($(eventObjSiblings[i]).css("height"));
                                    if (offsetPageX > boxleft && offsetPageX < (boxleft + boxwidth) && offsetPageY > boxtop && offsetPageY < (boxtop + boxheight)) {
                                        onTargetID = $(eventObjSiblings[i]).attr('id');
                                        var coffset = $(eventObjSiblings[i]).offset();
                                        _cx = coffset.left;
                                        _cy = coffset.top;
                                        _cw = parseInt($(eventObjSiblings[i]).css('width'));
                                        _ch = parseInt($(eventObjSiblings[i]).css('height'));
                                        var boxlist = eventObj.siblings();
                                        var cloneindex = boxlist.indexOf(eclone.get());
                                        var nindex = boxlist.indexOf($(eventObjSiblings[i]).get());
                                        var ecloneTop = eclone.css('top'),
                                        ecloneLeft = eclone.css('left'),
                                        ecloneID = eclone.attr('id');
                                        eclone.css({
                                            "top": $(eventObjSiblings[i]).css('top'),
                                            "left": $(eventObjSiblings[i]).css('left')
                                        });
                                        eclone.attr('id', $(eventObjSiblings[i]).attr('id'));
                                        if (cloneindex < nindex) {
                                            for (var index = nindex; index > cloneindex; index--) {
                                                if (index - 1 == cloneindex) {
                                                    $(boxlist[index]).css({
                                                        "top": ecloneTop,
                                                        "left": ecloneLeft
                                                    });
                                                    $(boxlist[index]).attr('id', ecloneID)
                                                } else {
                                                    $(boxlist[index]).css({
                                                        "top": $(boxlist[index - 1]).css('top'),
                                                        "left": $(boxlist[index - 1]).css('left')
                                                    });
                                                    $(boxlist[index]).attr('id', $(boxlist[index - 1]).attr('id'))
                                                }
                                            }
                                        } else {
                                            for (var index = nindex; index < cloneindex; index++) {
                                                if (index + 1 == cloneindex) {
                                                    $(boxlist[index]).css({
                                                        "top": ecloneTop,
                                                        "left": ecloneLeft
                                                    });
                                                    $(boxlist[index]).attr('id', ecloneID)
                                                } else {
                                                    $(boxlist[index]).css({
                                                        "top": $(boxlist[index + 1]).css('top'),
                                                        "left": $(boxlist[index + 1]).css('left')
                                                    });
                                                    $(boxlist[index]).attr('id', $(boxlist[index + 1]).attr('id'))
                                                }
                                            }
                                        }
                                        if (cloneindex < nindex) {
                                           eclone.insertAfter($(eventObjSiblings[i]))
                                        } else {
                                          eclone.insertBefore($(eventObjSiblings[i]))
                                        }
                                    }
                                }
                            }
                        }
                    }
                }).unbind("mouseup").bind("mouseup", function(e) {
                    if (_downfun) {
                        clearTimeout(_downfun)
                    }
                    if (e.button != 2 && _move) {
                        eventObj.css({
                            "opacity": 1,
                            "z-index": ''
                        });
                        eventObj.children().css("cursor", "pointer");
                        eventObj.css({
                            "top": eclone.css('top'),
                            "left": eclone.css('left'),
                            "border": ""
                        });
                        if (eventObj.hasClass('boxFixed')) {
                            eventObj.removeClass('boxFixed');
                            eventObj.find('.boxClose').css('display', 'block')
                        }
                        eventObj.attr('id', eclone.attr('id'));
                        eventObj.insertAfter(eclone);
                        if (onTargetID != '') {
                            if (eventObj.hasClass('boxVirtual')) {
                                if (eventObj.hasClass('boxCreate')) {
                                    var boxData = {
                                        title: getI18nMsg('boxCreateTitle'),
                                        isCreate: true
                                    }
                                }
                                PDI.appendDialbox(parseInt(onTargetID.replace('appBox_', '')), boxData);
                                self.loadBoxes()
                            } else {
                                PDI.moveDialbox(parseInt(onDragID.replace('appBox_', '')), parseInt(onTargetID.replace('appBox_', '')))
                            }
                        }
                        _move = false;
                        onDragID = '';
                        onTargetID = '';
                        eventObj.removeClass("boxDrag");
                        eclone.remove()
                    } else if (e.button != 2 && _down) {
                    	if (eventObj.attr('url') == '') {
                            return false
                        }
                        if (e.button == 0) {
                        	//chrome.tabs.update({url: eventObj.attr('url')})
                        	location.href =  eventObj.attr('url');
                        }
                    }
                    _down = false
                })
            },
            pageIndex: function() {
                var self = this;
                if (self.totalPage > 1) {
                    if (self.pageIndexSwitcher == '') {
                        self.pageIndexSwitcher = $('<div class="pageIndex"><div></div></div>');
                        self.pageIndexSwitcher.insertAfter(self.container)
                    }
                    self.pageIndexSwitcher.find('div').empty();
                    for (var i = 1; i <= self.totalPage; i++) {
                        self.pageIndexSwitcher.find('div').append($('<span index="' + i + '"></span>').bind('click',
                        function() {
                            self.loadBoxes($(this).attr('index'))
                        }))
                    }
                    self.pageIndexSwitcher.find('span').removeClass('selected');
                    self.pageIndexSwitcher.find("span[index='" + self.page + "']").addClass('selected')
                } else {
                    self.pageSwitcher = '';
                    if (self.pageIndexSwitcher != '') {
                        self.pageIndexSwitcher.remove()
                    }
                    self.pageIndexSwitcher = ''
                }
            },
            loadBoxes: function(pageSwitch) {
                var self = this;
                if (typeof pageSwitch == 'undefined' || (parseInt(pageSwitch) == pageSwitch && pageSwitch == self.page)) {
                    onDragID = '';
                    self.container.empty();
                    self.addBoxes();
                    self.positionBox();
                    return false
                }
                if (parseInt(pageSwitch) == pageSwitch) {
                    if (pageSwitch == self.page) {
                        return false
                    }
                    var _pageSwitch = pageSwitch > self.page ? 'next': 'pre';
                    _page = parseInt(pageSwitch);
                    pageSwitch = _pageSwitch
                } else {
                    _page = pageSwitch == "next" ? (self.page * 1) + 1 : (self.page * 1) - 1
                }
                if (_page < 1 || _page > self.totalPage) {
                    return false
                }
                self.page = _page;
                var distance = pageSwitch == "next" ? parseInt(self.containerWidth + self.containerLeft) : 0 - parseInt(self.containerWidth) - self.containerLeft;
                var allDistance = pageSwitch == "next" ? distance + self.containerLeft: distance - self.containerLeft;
                var containerClone = self.container.clone();
                containerClone.insertAfter(self.container);
                containerClone.css({
                    "opacity": 1,
                    "-webkit-transition": "left .4s ease-in, top .4s ease-in, opacity .4s ease-in"
                });
                self.container.css({
                    "display": "none",
                    "left": (self.containerLeft + distance * 1) + "px",
                }).removeClass(self.container.attr('class').replace('appDialbox ', '')).find('.appBox').not('.boxClone').not('.boxDrag').remove();
                self.addBoxes(pageSwitch);
                self.positionBox();
                self.container.css({
                    "display": "block"
                });
                window.setTimeout(function() {
                    containerClone.css({
                        "left": (self.containerLeft - 1 * distance) + "px",
                        "opacity": 1
                    })
                },
                0);
                window.setTimeout(function() {
                    self.container.css({
                        "-webkit-transition": "left .4s ease-in, top .4s ease-in, opacity .4s ease-in",
                        "left": self.containerLeft + "px"
                    }).removeClass(self.container.attr('class').replace('appDialbox ', '')).addClass('op_10')
                },
                0);
                window.setTimeout(function() {
                    self.container.removeClass(self.container.attr('class').replace('appDialbox ', '')).addClass('op_' + self.opacity * 10);
                    self.container.css({
                        "-webkit-transition": "",
                    });
                    containerClone.remove()
                },
                450);
                PDI.set('setup', 'dialBoxPage', self.page)
            }
        };
        return dialbox
    })()
})($);